import { RequestClient } from '@kunliu11/request'
import NProgress from '@/utils/progress'
import { useUserStoreHook } from '@/store/modules/user'
import router from '@/router'
import { ElMessage, ElNotification } from 'element-plus'
import type { AxiosResponse } from 'axios'

const request = new RequestClient({
  timeout: 100 * 1000, // 请求超时时间 100s
  withCredentials: true, // 允许跨域传递 cookie
  interceptorsConfig: {
    notification: {
      error: () =>
        ElNotification({
          message: 'downloadFailed',
          type: 'error'
        }),
      success: () =>
        ElNotification({
          message: 'downloadSuccess',
          type: 'success'
        }),
      loading: () =>
        ElNotification({
          message: 'downloading',
          type: 'info'
        })
    },
    message: {
      error: msg => ElMessage.error(msg)
    }
  },
  beforeRequestCallback: {
    fulfilled: config => {
      // NProgress.start()
      // 接口设置时间戳
      config.params = {
        ...config.params,
        timestamp: Date.now()
      }
      if (useUserStoreHook().accessToken) {
        config.headers.Authorization =
          'Bearer ' + useUserStoreHook().accessToken
      }
      return config
    },
    rejected: error => {
      return Promise.reject(error)
    }
  },
  beforeResponseCallback: {
    fulfilled: async response => {
      NProgress.done()
      if (response.data.code !== 0) {
        return Promise.reject(handleErrorMsg(response))
      }
      return await Promise.resolve(response.data)
    },
    rejected: async error => {
      NProgress.done()
      // 所有的响应异常 区分来源为取消请求/非取消请求
      if (error.response && error.response.status === 401) {
        // 跳转到登录页面
        router.push({ name: 'Login' })
      }
      return Promise.reject(error)
    }
  }
})

export function handleErrorMsg(response: AxiosResponse) {
  const data = response?.data
  if (data?.message) {
    if (Array.isArray(data.message)) {
      data.message = data.message[0]
    }
  }

  return data
}

export default request
